import 'package:video_compress/video_compress.dart';
import 'dart:io';

/**
 * @Description: 视频压缩
 * @Author: 下雨了
 * @CreateDate: 2022-02-10 10:19
 * @UpdateUser: 更新者
 * @UpdateDate:  2022-02-10 10:19
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
///
//
// dependencies:
//   video_compress: ^3.1.0
//

class VideoCompressUtils {
  //私有构造函数
  VideoCompressUtils._internal();

  //保存单例
  static final VideoCompressUtils _videoCompressUtils = VideoCompressUtils._internal();

  //工厂构造函数
  factory VideoCompressUtils() => _videoCompressUtils;

  /// 使用 video_compress 对视频 进行压缩
  Future<MediaInfo?> compressVideo(String path) async {
    MediaInfo? mediaInfo = await VideoCompress.compressVideo(
      path, //视频路径
      quality: VideoQuality.Res960x540Quality, // 压缩视频质量
      deleteOrigin: true, // 删除源文件
      startTime: 0, // 压缩视频的开始时间
      duration: 10, // 视频时间低于10秒的不压缩
      includeAudio: true, // 是否包含音频
      frameRate:30, // 压缩视频帧率
    );
    return mediaInfo;
  }

  /// 获取文件 缩略图
  Future<File> getFileThumbnail(
      String path,
      {int quality = 50, // default(100)
      int position = -1 // default(-1) 截取视频的时间 单位毫秒
      }) async {
    final thumbnailFile = await VideoCompress.getFileThumbnail(path, quality: quality, position: position);
    return thumbnailFile;
  }

  /// 获取 视频文件 时间  00:00:00 格式
  Future<String> getVideoDuration(String path) async {
    if (path == "") {
      return "00:00:00";
    }
    MediaInfo mediaInfo = await VideoCompress.getMediaInfo(path);
    double? d = mediaInfo.duration;
    String recordTimeStr = "";
    if (d != null) {
      Duration duration = Duration(milliseconds: d.toInt());
      var hour = duration.inHours;
      var minutes = duration.inMinutes - hour * 60;
      var seconds = duration.inSeconds - duration.inMinutes * 60;
      recordTimeStr = '${fixedIntString(hour, fixed: 2)}:${fixedIntString(minutes, fixed: 2)}:${fixedIntString(seconds, fixed: 2)}';
    }
    return recordTimeStr;
  }

  String fixedIntString(
      int a, {
        required int fixed,
      }) {
    var _str = a.toString();
    if (_str.length < fixed) {
      return _str.padLeft(fixed, '0');
    }
    return _str;
  }

  /// stop compressing the file that is currently being compressed.
  /// If there is no compression process, nothing will happen.
  Future<void> cancelCompression() async {
    await VideoCompress.cancelCompression();
  }

  /// delete the cache folder, please do not put other things
  /// in the folder of this plugin, it will be cleared
  Future<bool?> deleteAllCache() async {
    return await VideoCompress.deleteAllCache();
  }

  Future<void> setLogLevel(int logLevel) async {
    return await VideoCompress.setLogLevel(logLevel);
  }
}
